package com.desire.controller;

/**
 * @author LittleDesire
 * @description
 * @date 2022-04-28 周四 15:17
 * @since 17
 */

import com.desire.bean.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(value = "/user")
public class UsersController {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @RequestMapping("/add")
    public int addUser(Users user) {
        //新增数据
        String sql = "insert into user (id, name, age) value (?,?,?)";
        return jdbcTemplate.update(sql, user.getId(), user.getName(), user.getAge());
    }

    @RequestMapping("/del/{id}")
    public int delUser(@PathVariable Long id) {
        // 根据主键ID删除用户信息
        String sql = "DELETE FROM user WHERE id = ?";
        return jdbcTemplate.update(sql, id);
    }

    @RequestMapping("/update/{id}")
    public int updateUser(@PathVariable Long id, Users user) {
        // 根据主键ID修改用户信息
        String sql = "UPDATE user SET name = ? ,age = ? WHERE id = ?";
        return jdbcTemplate.update(sql, user.getName(), user.getAge(), id);
    }

    @RequestMapping("/getData")
    public List<Users> queryUser() {
        // 查询所有用户
        String sql = "select * from user";
        return jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(Users.class));
    }

    @RequestMapping("/get/{id}")
    public Users getUser(@PathVariable Long id) {
        // 根据主键ID查询用户
        String sql = "select * from user where id = ?";
        return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Users.class));
    }


}
